<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Models as Models;

class SmileController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */

    //遍历文件夹并把文件名写入数据库
    public function getFileName()
    {
        $smileObj = new Models\Smiles();
        $file_dir = 'images/smile';//表情包的目录地址
        //PHP遍历文件夹下所有文件
        $handle=opendir($file_dir.".");
        $file_num = 0;
        while (false !== ($file = readdir($handle)))
        {
            $file=iconv("gb2312","utf-8",$file);
            if ($file != "." && $file != "..") {
                //文件名存入数据库
                $insert_array = array(
                    'url' => $file,
                    'created_time' => time(),
                    'updated_time' => time(),
                );
                $insert_result = $smileObj->addUrl($insert_array);
                $file_num ++;
            }
        }
        closedir($handle);
        echo $file_num;
    }

    //修改文件名
    public function newSmileName(Request $request)
    {
        $return_json = array (
            'status' => 0,
            'message' => '',
            'result' => array ()
        );
        $id = $request->id;
        $new_url = $request->url;
        $smileObj = new Models\Smiles();
        $smile = $smileObj->getSmileById($id);
        $path = 'images/smile/';
        $rename_reuslt = rename(iconv('UTF-8','GBK',$path.$smile->url), iconv('UTF-8','GBK',$path.$new_url));
        if($rename_reuslt){
            $update_array = array(
                'url' => $new_url,
                'updated_time' => time()
            );
            $update_result = $smileObj->updateSmileById($id,$update_array);
        }
        return $return_json;
    }
}
